package com.api.phm.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.api.common.config.ApiConfig;
import com.api.common.utils.DateUtils;
import com.api.phm.domain.query.RealTimeQuery;
import com.api.phm.domain.vo.RealTimePageVo;
import com.api.phm.mapper.RealTimeMapper;
import com.api.phm.service.IRealTimeService;
import com.api.phm.util.CommandUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class RealTimeServiceImpl implements IRealTimeService {
    /**
     * 系统基础配置
     */
    @Autowired
    private ApiConfig apiConfig;

    @Autowired
    private RealTimeMapper realTimeMapper;

    private final String fileName = "\\bat\\getData.bat";

    @Override
    public List<List> realTimeData(RealTimePageVo realTimePageVo) {
//        Date date = new Date();
        Date date = realTimePageVo.getStartTime();
        long timeLong = date.getTime();

        String dattime = DateUtils.parseDateToStr("yyyyMMddHHmm", date) + "00";
//        dattime = "20240517165500";
//        String filePath = apiConfig.getRealTimeFile();
        String filePath = apiConfig.getProjectPath() + fileName;
        System.out.println("filePath:" + filePath);

        RealTimeQuery realTimeQuery = realTimeMapper.realTimeDevices(realTimePageVo);
        realTimeQuery.decryptPlcPwd();
        String datFilePath = realTimeQuery.getPlcCode() + "_" + realTimeQuery.getElementCode() + "\\" + DateUtils.parseDateToStr("yyyyMMdd", date) + "\\";

        String cmdOrder = filePath
                + " " + realTimeQuery.getPlcIp()
                + " " + realTimeQuery.getPlcUser()
                + " " + realTimeQuery.getPlcPwd()
                + " " + datFilePath
                + " " + realTimeQuery.getElementNum()
                + " " + dattime;
        System.out.println("cmdOrder:" + cmdOrder);
        Map<String, Object> map = CommandUtils.runCmdByWindows(cmdOrder, "GBK", 5);
        List<String> list = JSONArray.parseArray(map.get("data").toString(), String.class);
//        List<Map<Long, Double>> timeList = new ArrayList<>();
        List<List> timeList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
//            Map<Long, Double> timeMap = new HashMap<>();
//            Map<String,Object> timeMap = new HashMap<>();
            List timeMap = new ArrayList();
            Long key = timeLong + (i * 20L);
            Double s = Double.valueOf(list.get(i));
//            timeMap.put("time", key);
//            timeMap.put("value", key);
            timeMap.add(key);
            timeMap.add(s);
            timeList.add(timeMap);
        }
        return timeList;
    }
}
